<?php

/**
 * userHandler
 * The class that handles user related actions such as logging in. 
 */
class userHandler
{
	private static $typeArray = array('', 'leerlingen', 'docenten', 'klassetv');

	/**
	 * verifyLogin
	 * @param string $session $_SESSION value
	 * 
	 * @return array Returns an array of the user's details if the user is logged in
	 * @return boolean Returns false if the user is not logged in
	 */
	static function verifyLogin($session)
	{
		// If the user isn't logged in, return false
		if(is_null($session))
		{
			return false;
		}

		// Get the text representation of the number type
		$split = explode(":", $session);
		$type = self::$typeArray[$split[0]];

		// If the user is klassetv, return the array for the administrator
		if($type == 'klassetv')
		{
			return array('type' => $split[0], 'id' => null, 'classid' => null, 'firstname' => 'Beheerder', 'lastname' => 'KlasseTV', 'username' => 'KlasseTV');
		}

		$userQuery = mysql_query("SELECT * FROM " . $type . " WHERE `id`='" . $split[1] . "'");

		if(mysql_num_rows($userQuery) != 1)
		{
			return false;
		}

		$user = mysql_fetch_assoc($userQuery);
		extract($user);

		return array('type' => $split[0], 'id' => $id, 'classid' => $klas_id, 'firstname' => $voornaam, 'lastname' => $achternaam, 'username' => $gebruikersnaam);
	}

	/**
	 * logIn()
	 * Attempts to set a user session with given type and id
	 * 
	 * @param string $type Text representation of the type of user
	 * @param int $id The ID of the user
	 * @return boolean Returns true when session was set, false if userdetails don't match
	 */
	static function logIn($type, $id)
	{
		if(mysql_num_rows(mysql_query("SELECT * FROM `" . $type . "` WHERE `id`='" . $id . "'")) == 1)
		{
			$_SESSION['userSession'] = array_search($type, self::$typeArray) . ':' . $id;
			return true;
		}

		return false;
	}

	/**
	 * getUser()
	 * Returns the userdetails of the given data
	 * 
	 * @param string $type Text representation of the user type
	 * @param string $username User's username
	 * @param type $password User's password
	 * @return boolean/array Returns boolean (False) if the user wasn't found, array with userdetails if user was found 
	 */
	static function getUser($type, $username, $password)
	{
		$userQuery = mysql_query("SELECT * FROM `" . $type . "` WHERE `gebruikersnaam`='" . $username . "' AND `wachtwoord`='" . $password . "'");

		if(mysql_num_rows($userQuery) == 1)
		{
			return mysql_fetch_assoc($userQuery);
		}
		return false;
	}

	/**
	 * loginCheck()
	 * Simple login check to see if the user matches the required type of user. If not, the 403 page is loaded.
	 * 
	 * @param string $type Text representation of the required user type.
	 */
	static function loginCheck($type)
	{
		if(User::getType() != $type)
		{
			require ROOT . 'paginas/errors/403.php';
		}
	}
}